<script setup>
import { defineEmits, ref, watch, nextTick } from 'vue'
import { LeftOutlined, ReloadOutlined } from '@ant-design/icons-vue'
import markdown from './utils/markdown'
import { useElementBounding } from '@vueuse/core'
import { message } from 'ant-design-vue'
import utils from '@/common/utils/utils'
import { streamFetch } from "@/common/utils/streamFetch"
import defaultSetting from "@/common/utils/defaultSetting"

let BASE_URL = defaultSetting.requestDomain;
if (process.env.NODE_ENV === "development") {
    BASE_URL = BASE_URL + "/api";
}

const emit = defineEmits(['back'])
const visible = ref(true)

const onBack = () => {
    emit('back')
}

const index = ref(0)
const toolsModuleRef = ref()
const { top, height, width } = useElementBounding(toolsModuleRef)
const mindmapRef = ref()

const examples = [
    '商业计划书撰写要点',
    '制定团队OKR注意事项',
    '《启示录》读书笔记',
    '长沙旅游注意事项',
    '设计师必备工具清单'
]

const defaultAnswer = `- 制定团队 OKR 注意事项
  - 确定明确的目标
    - 对齐公司目标
    - 具体可衡量的指标
  - 设定挑战性的关键结果
    - 具有明确的结果导向
    - 激励团队成员
  - 确保可衡量和跟踪
    - 使用量化指标进行评估
    - 确定进度跟踪方法
  - 促进透明度和沟通
    - 共享 OKR 目标和结果
    - 定期更新和讨论进展
  - 灵活调整和优化
    - 根据实际情况进行调整
    - 学习和改进 OKR 设定过程
  - 激励和奖励团队成员
    - 基于 OKR 实现给予奖励
    - 与个人绩效评估相关联
`

const createExample = () => {
    content.value = examples[index.value]
    index.value = index.value + 1

    if (index.value >= examples.length) {
        index.value = 0
    }
}

const content = ref('')
const answer = ref(defaultAnswer)

watch([visible, height, width, answer], () => {
    nextTick(() => {
        mindmapRef.value.contentWindow.postMessage({
            message: 'mindmap',
            callFunc: 'renderer.setRootNodeCenter'
        })
    })
})

const setMindmapData = (data) => {
    mindmapRef.value.contentWindow.postMessage({
        message: 'mindmap',
        callFunc: 'setData',
        args: [data]
    })
}


const createMindmapMarkdown = async () => {
    if (content.value == '') {
        return message.error('请输入内容')
    }

    answer.value = 'AI组织语言中,请稍后'

    let params = {
        generate_type: 'siweidaotu',
        org_id: utils.getOrgId(),
        user_token: utils.getToken(),
        role_name: content.value,
        cur_env: utils.isMobile()
            ? "h5"
            : import.meta.env.ELECTRON
                ? "desktop"
                : "pc",
    }

    let response = ''
    let regex = /^\s*-\s+(.+)/gm;

    const { responseText } = await streamFetch({
        url: `${BASE_URL}/work_ai/chat/prompt/generated`,
        data: params,
        onMessage: (text) => {
            if (utils.isJSONStr(text)) {
                let res = JSON.parse(text);

                if (utils.isObject(res) && res.msg) {
                    message.error(res.msg)
                    answer.value = res.msg
                    return;
                }
            }

            if (response == '') {
                answer.value = ''
            }

            response += text

            const matches = response.match(regex);
            const result = matches ? matches.join("\n") : "";
            answer.value = result
        },
    }).catch((err) => {
        return {
            responseText: '',
        };
    })

    if (responseText) {
        const matches = responseText.match(regex);
        const result = matches ? matches.join("\n") : "";
        answer.value = result
    }
}

watch(answer, (response) => {
    if (response) {
        const matches = response.match(/^\s*-\s+(.+)/gm);
        const result = matches ? matches.join("\n") : "";

        if (result) {
            let node = markdown.transformMarkdownTo(result)
            setMindmapData(node)
        }
    }
})
</script>

<template>
    <div class="tools-module h-full" ref="toolsModuleRef">
        <div class="h-full mindmap-ai" :class="{ hide: !visible }">
            <div class="expand_arrow absolute" @click="() => visible = !visible">
                <div class="arrow" :class="{ right: !visible }"></div>
            </div>
            <div class="overflow-hidden">
                <div @click="onBack" class="cursor-pointer">
                    <LeftOutlined /> 返回
                </div>
                <div class="mt-20 tools-title">
                    AI 思维导图
                </div>
            </div>
            <div class="tools-content mt-20 overflow-hidden">
                <div class="tools-content-title flex justify-between align-center">
                    <div>
                        内容主题
                    </div>
                    <div style="color:#4c83fc;" class="cursor-pointer" @click="createExample">
                        <ReloadOutlined /> 示例推荐
                    </div>
                </div>
                <div class="mt-10">
                    <a-textarea v-model:value="content" placeholder="请输入您想要生成内容的描述，AI将为您输出一份完整的思维导图"
                        style="padding: 10px;" :autosize="{ minRows: 3, maxRows: 3 }"></a-textarea>
                </div>
                <div class="mt-15">
                    <a-button block type="primary" @click="createMindmapMarkdown">生成思维导图</a-button>
                </div>
            </div>
            <div class="tools-answer mt-10 overflow-hidden">
                <div class="tools-answer-title">
                    内容大纲
                </div>
                <div class="mt-10">
                    <a-textarea v-model:value="answer" placeholder="# Ai智能工具
## 部分功能
- 支持AI聊天
- 支持微应用
- 支持自定义创建
- 支持DEL绘画
- 支持Midjourney
- 更多功能等你探索......

## 更多内容
- 在上面输入您想要生成的内容
- 点击生成大纲即可" class="tools-answer-textarea" :autosize="{ minRows: 13, maxRows: 13 }"></a-textarea>
                </div>
            </div>
        </div>
        <Teleport to="body">
            <iframe ref="mindmapRef" id="mindMap" src="/mindmap/index.html"
                style="position: absolute;display: block;border: 0px;left: auto;right: 0px;"
                :style="{ top: top + 'px', height: height + 'px', width: `calc(100% - ${visible ? 463 : 201}px)` }"></iframe>
        </Teleport>
    </div>
</template>

<style lang="less" scoped>
.mindmap-ai {
    width: 262px;
    z-index: 100;
    padding: 18px 14px;
    background: #dfe8f2;
    position: relative;

    &.hide {
        width: 0;
        padding: 0;
        background: none;

        .expand_arrow {
            right: -28px;
        }
    }

    .expand_arrow {
        display: block !important;
        color: #fff;
        right: -14px;
        top: 50%;
        width: 28px;
        height: 28px;
        background-color: #fff;
        border-radius: 50%;
        box-shadow: 0 0 1px 1px #f1f1f6 inset;
        cursor: pointer;
        z-index: 300;

        .arrow {
            display: block !important;
            width: 10px;
            height: 10px;
            border-top: 2px solid #b6b6b6;
            border-left: 2px solid #b6b6b6;
            position: absolute;
            top: 9px;
            left: 10px;
            -webkit-transform: rotate(-45deg);
            transform: rotate(-45deg);
            cursor: pointer;

            &.right {
                -webkit-transform: rotate(135deg);
                transform: rotate(135deg);
                left: 6px;
            }
        }
    }

    .tools-title {
        font-size: 20px;
        font-weight: 700;
        color: #333;
    }

    .tools-content .tools-content-title,
    .tools-answer .tools-answer-title {
        font-size: 12px;
        font-weight: 400;
        color: #333;
    }

    .tools-answer-textarea {
        height: 300px !important;
        max-height: 300px !important;
    }
}
</style>